package com.ruoyi.system.service.impl;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.zip.GZIPInputStream;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.Weather;
import com.ruoyi.system.service.IWeatherService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.Arrays;
import java.util.Collections;

/**
 * 天气服务实现类
 */
@Service
public class WeatherServiceImpl implements IWeatherService {
    private static final Logger log = LoggerFactory.getLogger(WeatherServiceImpl.class);
    
    private final RestTemplate restTemplate = new RestTemplate();
    private final ObjectMapper objectMapper = new ObjectMapper();
    
    // 南宁市的天气ID
    private static final String NANNING_CITY_ID = "101300101";

    private Weather cachedWeather;
    
    @Value("${qweather.api.key:9b28405845ed4996ba721fb5de5e7084}")
    private String apiKey;

    @Value("${qweather.api.url:https://nf63yvmv6c.re.qweatherapi.com/v7/weather/now}")
    private String apiUrl;

    /**
     * 从压缩的字节数组中解压并读取内容
     * 
     * @param compressedData 压缩的数据
     * @return 解压后的字符串
     */
    private String decompressGzip(byte[] compressedData) throws IOException {
        if (compressedData == null || compressedData.length == 0) {
            return "";
        }
        
        try (ByteArrayInputStream bis = new ByteArrayInputStream(compressedData);
             GZIPInputStream gis = new GZIPInputStream(bis);
             ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            
            byte[] buffer = new byte[1024];
            int len;
            while ((len = gis.read(buffer)) > 0) {
                bos.write(buffer, 0, len);
            }
            
            return bos.toString("UTF-8");
        }
    }

    /**
     * 获取南宁的天气数据
     */
    @Override
    public Weather getWeatherData(String cityId) {
        try {
            String url = apiUrl + "?location=" + cityId + "&key=" + apiKey;
            log.info("请求天气API: {}", url);

            HttpHeaders headers = new HttpHeaders();
            headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
            headers.set("Accept-Encoding", "gzip");
            headers.set("User-Agent", "Mozilla/5.0");
            
            HttpEntity<String> entity = new HttpEntity<>(headers);

            ResponseEntity<byte[]> response = restTemplate.exchange(url, HttpMethod.GET, entity, byte[].class);
            
            if (response.getStatusCode().is2xxSuccessful()) {
                byte[] responseBody = response.getBody();
                
                if (responseBody != null && responseBody.length > 0) {
                    // 尝试解压GZIP数据
                    String jsonResponse = decompressGzip(responseBody);
                    log.info("解压后的API响应: {}", jsonResponse);
                    
                    if (StringUtils.isEmpty(jsonResponse)) {
                        log.error("API返回内容为空或解压失败");
                        return null;
                    }
                    
                    JsonNode root = objectMapper.readTree(jsonResponse);
                    
                    // 检查API响应是否成功
                    String code = root.path("code").asText();
                    if (!"200".equals(code)) {
                        log.error("和风天气API错误: {}", jsonResponse);
                        return null;
                    }
                    
                    JsonNode now = root.path("now");
                    if (!now.isMissingNode()) {
                        Weather weather = new Weather();
                        weather.setCityName("南宁");
                        weather.setText(now.path("text").asText());
                        weather.setTemp(now.path("temp").asText());
                        weather.setFeelsLike(now.path("feelsLike").asText());
                        weather.setHumidity(now.path("humidity").asText());
                        weather.setWindDir(now.path("windDir").asText());
                        weather.setWindScale(now.path("windScale").asText());
                        weather.setWindSpeed(now.path("windSpeed").asText());
                        weather.setUpdateTime(new Date());
                        
                        // 更新缓存
                        this.cachedWeather = weather;
                        return weather;
                    }
                }
            }
            
            log.error("获取天气数据失败: {}", response.getStatusCode());
            return null;
        } catch (Exception e) {
            log.error("获取天气数据时发生错误", e);
            return null;
        }
    }

    /**
     * 获取最新缓存的天气数据
     */
    @Override
    public Weather getLatestWeather() {
        if (cachedWeather == null) {
            // 如果没有缓存数据，则获取新数据
            return getWeatherData(NANNING_CITY_ID);
        }
        return cachedWeather;
    }

    /**
     * 更新缓存中的天气数据
     */
    @Override
    public void updateWeatherData() {
        log.info("正在从和风天气API更新天气数据");
        getWeatherData(NANNING_CITY_ID);
    }
} 